package com.xaicode.learn.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * file -> channel -> content
 *
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/13 0013 1:36
 */
@Slf4j
public class NIOFileChannel02 {

    private static final String FILE_PATH = "logs" + File.separator;

    public static void main(String[] args) throws IOException {

        // create file output stream
        File file = new File(FILE_PATH + "NIOFileChannel01.txt");
        FileInputStream inputStream = new FileInputStream(file);
        // get file channel (FileChannelImpl)
        FileChannel fileChannel = inputStream.getChannel();
        // create buffer
        // ByteBuffer.hb fill with 0
        ByteBuffer byteBuffer = ByteBuffer.allocate(((int) file.length()));
        // read to buffer
        fileChannel.read(byteBuffer);

        log.info("file content is [{}]", new String(byteBuffer.array()));

        inputStream.close();
    }

}
